package com.zjy.financialsystemjavafx.controller;

import com.zjy.financialsystemjavafx.model.entity.Category;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import com.zjy.financialsystemjavafx.util.SessionContext;
import com.zjy.financialsystemjavafx.model.entity.User;
import com.zjy.financialsystemjavafx.service.UserService;
import com.zjy.financialsystemjavafx.service.CategoryService;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ChoiceDialog;
import java.util.Arrays;
import java.util.Optional;

import java.io.IOException;

/**
 * 设置界面控制器
 */
public class SettingsController {

    // 个人信息修改
    @FXML private TextField usernameField;
    @FXML private TextField emailField;
    @FXML private TextField phoneField;
    @FXML private Button updateInfoButton;

    // 密码修改
    @FXML private PasswordField oldPasswordField;
    @FXML private PasswordField newPasswordField;
    @FXML private PasswordField confirmPasswordField;
    @FXML private Button changePasswordButton;

    // 分类管理
    @FXML private TableView<Category> categoryTable;
    @FXML private TableColumn<Category, Integer> catIdColumn;
    @FXML private TableColumn<Category, String> catNameColumn;
    @FXML private TableColumn<Category, String> catTypeColumn;
    @FXML private TableColumn<Category, String> catDescColumn;
    @FXML private Button addCatButton;
    @FXML private Button editCatButton;
    @FXML private Button deleteCatButton;

    // 返回仪表盘
    @FXML private Button backButton;

    private ObservableList<Category> categoryList = FXCollections.observableArrayList();
    private UserService userService;
    private CategoryService categoryService;
    private int currentUserId;

    @FXML
    private void initialize() {
        userService = new UserService();
        categoryService = new CategoryService();
        // 加载当前用户信息
        User current = SessionContext.getCurrentUser();
        currentUserId = current.getUserId();
        usernameField.setText(current.getUsername());
        emailField.setText(current.getEmail());
        phoneField.setText(current.getPhoneNumber());

        // 配置分类表格
        catIdColumn.setCellValueFactory(new PropertyValueFactory<>("categoryId"));
        catNameColumn.setCellValueFactory(new PropertyValueFactory<>("categoryName"));
        catTypeColumn.setCellValueFactory(new PropertyValueFactory<>("categoryType"));
        catDescColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        refreshCategoryTable();
    }

    /**
     * 刷新分类列表
     */
    private void refreshCategoryTable() {
        try {
            categoryList.clear();
            categoryList.addAll(categoryService.getCategories(currentUserId));
            categoryTable.setItems(categoryList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleUpdateInfo(ActionEvent event) {
        String email = emailField.getText();
        String phone = phoneField.getText();
        try {
            if (userService.updateUserInfo(currentUserId, email, phone)) {
                // 更新 SessionContext 中的数据
                User current = SessionContext.getCurrentUser();
                current.setEmail(email);
                current.setPhoneNumber(phone);
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("更新信息");
                alert.setHeaderText(null);
                alert.setContentText("用户信息已更新");
                alert.showAndWait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleChangePassword(ActionEvent event) {
        String oldPwd = oldPasswordField.getText();
        String newPwd = newPasswordField.getText();
        String confirmPwd = confirmPasswordField.getText();
        if (!newPwd.equals(confirmPwd)) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("密码错误");
            alert.setHeaderText(null);
            alert.setContentText("新密码与确认密码不一致");
            alert.showAndWait();
            return;
        }
        try {
            boolean ok = userService.changePassword(currentUserId, oldPwd, newPwd);
            Alert alert;
            if (ok) {
                alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("修改密码");
                alert.setHeaderText(null);
                alert.setContentText("密码修改成功");
            } else {
                alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("修改密码");
                alert.setHeaderText(null);
                alert.setContentText("旧密码不正确");
            }
            alert.showAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleAddCategory(ActionEvent event) {
        // 输入分类名称
        TextInputDialog nameDialog = new TextInputDialog();
        nameDialog.setTitle("添加分类");
        nameDialog.setHeaderText(null);
        nameDialog.setContentText("请输入分类名称：");
        Optional<String> nameOpt = nameDialog.showAndWait();
        if (!nameOpt.isPresent()) return;
        String name = nameOpt.get();
        // 选择分类类型
        ChoiceDialog<String> typeDialog = new ChoiceDialog<>("Expense", Arrays.asList("Expense", "Income"));
        typeDialog.setTitle("添加分类");
        typeDialog.setHeaderText(null);
        typeDialog.setContentText("请选择类型：");
        Optional<String> typeOpt = typeDialog.showAndWait();
        if (!typeOpt.isPresent()) return;
        String type = typeOpt.get();
        // 输入描述
        TextInputDialog descDialog = new TextInputDialog();
        descDialog.setTitle("添加分类");
        descDialog.setHeaderText(null);
        descDialog.setContentText("请输入描述（可选）：");
        Optional<String> descOpt = descDialog.showAndWait();
        String desc = descOpt.orElse("");
        try {
            if (categoryService.addCategory(currentUserId, name, type, desc)) {
                refreshCategoryTable();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleEditCategory(ActionEvent event) {
        Category selected = categoryTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        // 编辑名称
        TextInputDialog nameDialog = new TextInputDialog(selected.getCategoryName());
        nameDialog.setTitle("编辑分类");
        nameDialog.setHeaderText(null);
        nameDialog.setContentText("分类名称：");
        Optional<String> nameOpt = nameDialog.showAndWait();
        if (!nameOpt.isPresent()) return;
        selected.setCategoryName(nameOpt.get());
        // 编辑类型
        ChoiceDialog<String> typeDialog = new ChoiceDialog<>(selected.getCategoryType(), Arrays.asList("Expense", "Income"));
        typeDialog.setTitle("编辑分类");
        typeDialog.setHeaderText(null);
        typeDialog.setContentText("分类类型：");
        Optional<String> typeOpt = typeDialog.showAndWait();
        if (!typeOpt.isPresent()) return;
        selected.setCategoryType(typeOpt.get());
        // 编辑描述
        TextInputDialog descDialog = new TextInputDialog(selected.getDescription());
        descDialog.setTitle("编辑分类");
        descDialog.setHeaderText(null);
        descDialog.setContentText("描述：");
        Optional<String> descOpt = descDialog.showAndWait();
        selected.setDescription(descOpt.orElse(""));
        try {
            if (categoryService.updateCategory(selected, currentUserId)) {
                refreshCategoryTable();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleDeleteCategory(ActionEvent event) {
        Category selected = categoryTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        try {
            if (categoryService.deleteCategory(selected.getCategoryId(), currentUserId)) {
                refreshCategoryTable();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSelectWarning() {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("未选择");
        alert.setHeaderText(null);
        alert.setContentText("请先选择一条分类记录");
        alert.showAndWait();
    }

    @FXML
    private void handleBack(ActionEvent event) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/SettingsView.fxml"));
            // Should go back to Dashboard instead of loading Settings again
            root = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/Dashboard.fxml"));
            Stage stage = (Stage) backButton.getScene().getWindow();
            stage.setTitle("个人财务管家 - 仪表盘");
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载仪表盘界面");
            alert.showAndWait();
        }
    }
} 